package com.anycl.customer.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * JDBC工具类
 */
@Slf4j
public class JDBCUtil {

    private static final String driverClass;
    private static final String url;
    private static final String username;
    private static final String password;

    /**
     * 加载属性文件
     */
    static {
        Properties properties = new Properties();
        InputStream is = JDBCUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
        try {
            properties.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        driverClass = properties.getProperty("driverClass");
        url = properties.getProperty("url");
        username = properties.getProperty("username");
        password = properties.getProperty("password");
    }

    /**
     * 注册驱动
     */
    private static void loadDriver() throws ClassNotFoundException {
        Class.forName(driverClass);
    }

    /**
     * 获得连接
     */
    public static Connection getConnection() throws ClassNotFoundException, SQLException {
        loadDriver();
        return DriverManager.getConnection(url, username, password);
    }

    /**
     * 释放资源
     */
    public static void release(PreparedStatement pst, Connection conn)  {
        try {
            if (pst != null)
                releasePreparedStatement(pst);
            if (conn != null)
                releaseConnection(conn);
        } catch (SQLException e) {
            log.info("JDBC释放资源失败" + e.getMessage());
        }
    }

    public static void release(ResultSet rs,PreparedStatement pst, Connection conn)  {
        try {
            if (pst != null)
                releasePreparedStatement(pst);
            if (conn != null)
                releaseConnection(conn);
            if (rs != null)
                releaseResultSet(rs);
        } catch (SQLException e) {
            log.info("JDBC释放资源失败" + e.getMessage());
        }
    }

    private static void releasePreparedStatement(PreparedStatement pst) throws SQLException {
        pst.close();
    }

    private static void releaseConnection(Connection conn) throws SQLException {
        conn.close();
    }

    private static void releaseResultSet(ResultSet rs) throws SQLException {
        rs.close();
    }
}
